package com.delivery.www.dao.DaoImpl;

import com.delivery.www.dao.BaseDao;
import com.delivery.www.dao.CommentDao;
import com.delivery.www.po.Comment;
import com.delivery.www.util.JdbcUtils;

import java.sql.Connection;
import java.util.List;

/**
 * @author 12970
 */
public class CommentDaoImpl implements CommentDao {
    @Override
    public int doComment(int storeId, int userId, String content, int belongsCommentId, int userIdentity) {
        Connection connection = JdbcUtils.getConnection();
        Object[] params = {storeId, userId, content, belongsCommentId, userIdentity};
        String sql = "insert into comment (store_id,user_id,content,belongs_comment_id,user_identity) values(?,?,?,?,?)";
        int excute = 0;
        if (connection != null) {
            excute = BaseDao.executeUpdate(connection, sql, params);
            if (excute > 0) {
                Object[] objects = {storeId};
                String s = "update store set comment_num = comment_num + 1 where store_id = ?";
                BaseDao.executeUpdate(connection, s, objects);
            }
            JdbcUtils.closeResource(connection, null, null);
        }
        return excute;
    }

    @Override
    public List<Comment> getComment(int storeId) {
        Connection connection = JdbcUtils.getConnection();
        List<Comment> comments = null;
        Object[] params = {storeId};
        String sql = "select c.comment_id,content,belongs_comment_id,user_identity,u.user_name from comment c inner join user u on u.user_id = c.user_id where c.store_id = ?";
        if (connection != null) {
            comments = BaseDao.getList(connection, Comment.class, sql, params);
        }
        return comments;
    }

    @Override
    public int deleteComment(int commentId, int storeId) {
        Connection connection = JdbcUtils.getConnection();
        Object[] params = {commentId};
        String sql = "delete from comment where comment_id = ?";
        int i = 0;
        if (connection != null) {
            i = BaseDao.executeUpdate(connection, sql, params);
            if (i > 0) {
                Object[] objects = {storeId};
                String s = "update store set comment_num = comment_num - 1 where store_id = ?";
                BaseDao.executeUpdate(connection, s, objects);
            }
        }
        JdbcUtils.closeResource(connection, null, null);
        return i;
    }
}
